package com.ruoyi.common.utils;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.http.HttpClientUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class CommonHelper {

    public static Object getMethod(String classname, String methodName,Object[] param) {
        Method method = null;
        try {
            Class supplierClass = Class.forName(classname);
            Method[] methods = supplierClass.getMethods();
            for(Method method1 : methods) {
                if(methodName.equals(method1.getName())) {
                    method = method1;
                    break;
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            return method.invoke(classname,param);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }

    }


    public static String getNettyBackBody(String imei, byte[] bit, String requestUrl,String communicationType) {
        try {
            Map<String,String> map = new HashMap<>();
            map.put("imei",imei);
            map.put("data", convertString(bit));
            map.put("communicationType", communicationType);//增加通讯类型
            System.out.println(map);
            String s = HttpClientUtil.sendHttpPost(requestUrl, map);
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (Integer.parseInt(jsonObject.getString("status")) == 1){
                return jsonObject.getString("requestId");
            }else {
                return null;
            }
        }catch (Exception e){
            return null;
        }


    }

    public static String getDbNettyBackBody(String imei, byte[] bit, String requestUrl,String communicationType) {
        try {
            Map<String,String> map = new HashMap<>(4);
            map.put("imei",imei);
            map.put("data", convertString(bit));
            //增加通讯类型//增加通讯类型
            map.put("communicationType", communicationType);
            System.out.println(map);
            String s = HttpClientUtil.sendHttpPost(requestUrl, map);
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (Objects.equals(jsonObject.getInteger("status"), 1)){
                return jsonObject.getString("requestId");
            } else if (Objects.equals(jsonObject.getInteger("status"), 0)) {
                return jsonObject.getString("downDataId");
            } else {
                return null;
            }
        }catch (Exception e){
            return null;
        }


    }


    /**
     * 通用发送MQTT命令
     * @param values 已经包装好的数据命令
     * @param requestUrl netty的 MQTT 请求接口路径
     * @param communicationType 通讯类型，对应大表档案表表中的communication_type字段，6 代表是德高服务器上的mqtt服务
     * @param topic 下发命令的主题，存储于设备的communication_confin字段中
     * @return
     */
    public static String sendMqttMsg(Map<String,Object> values, String requestUrl,String communicationType,String topic) {
        try {
            Map<String,String> map = new HashMap<>();
            map.put("msg", JSONObject.toJSONString(values));
            map.put("communicationType", communicationType);//通讯类型
            map.put("topic", topic);//订阅的主题
            String s = HttpClientUtil.sendHttpPost(requestUrl, map);
            JSONObject jsonObject = JSONObject.parseObject(s);
            return jsonObject.getString("msg");
        }catch (Exception e){
            return null;
        }


    }


    public static String convertString(byte[] data){
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<data.length; i++){
            String s = Integer.toHexString(data[i] & 0xff);
            s = s.length()<2 ?("0"+s):s;
            sb.append(s);
        }
        return sb.toString();
    }

    public static String getCmdResponseBody(String imei, String uuid, int i, int timeout, String ip, int port) {
        String updata = "";
        try {
            String sendParam = "imei=" + imei + "&requestID=" + uuid;
            String sendDataStatus = HttpClientUtil.sendHttpPost("http://" + ip + ":" + port + "/swdegao_iot_mgt_server-0.0.1-SNAPSHOT/netty/commandResponse",
                    sendParam);
            if (!sendDataStatus.isEmpty() && !sendDataStatus.equals("")) {
                JSONArray send_obj = JSONArray.parseArray(sendDataStatus);
                if (send_obj.size() >= 1) {
                    String body = send_obj.getString(send_obj.size() - 1);
                    updata = JSONObject.parseObject(body).getString("upData");
                } else {
                    if (i <= timeout * 10) {
                        i++;
                        Thread.sleep(100);
                        updata = getCmdResponseBody(imei, uuid, i,timeout, ip, port);
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return updata;
    }

    public static ArrayList<String> getCmdResponseBody(String imei, String uuid, int i, int timeout, String responseUrl, Long waitTime) {
        ArrayList<String> updata = new ArrayList<>();
        try {
            for (int l = 0; l < 10; l++) {
                String sendParam = "imei=" + imei + "&requestID=" + uuid;
                String sendDataStatus = HttpClientUtil.sendHttpPost(responseUrl, sendParam);
                if (StringUtils.isNotBlank(sendDataStatus)){
                    JSONArray send_obj = JSONArray.parseArray(sendDataStatus);
                    for (int j = 0; j < send_obj.size(); j++) {
                        updata.add(JSONObject.parseObject(send_obj.getString(j)).getString("upData"));
                    }
                    break;
                }
                Thread.sleep(waitTime);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return updata;

    }



    /**
     * bcd码,示例：109230700049-》0x70 0x30 0x92 0x10 ·······
     * @param ad
     * @return
     */
    public static byte[] getByte(String ad)
    {

        byte[] bit = new byte[7];
        int length = ad.length();
        if(ad.length()<14){
            for(int j=0; j<14-length; j++){
                ad = "0"+ad;
            }
        }
        for (int i = 0; i < 7; i++)
        {
            String temp = ad.substring(i * 2, i * 2+2);
            bit[6-i] = (byte)Integer.parseInt(temp,16);
        }
        return bit;
    }
}
